package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.push.api.vo.request.EnableDisableScheduleVo;
import com.cloudbroker.bcs.csvc.push.api.vo.request.PushReportVo;
import com.cloudbroker.bcs.csvc.push.api.vo.request.UpdateScheduleVo;
import com.cloudbroker.bcs.csvc.push.api.vo.response.PushReportBack;
import com.cloudbroker.bcs.csvc.push.api.vo.response.PushReportData;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.AdminPushBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.PushBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.PushListBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.PushListData;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.vo.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.NotifyForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.TagsAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.TagsRemoveForm;
import com.cloudbroker.bcs.platform.ltb.middle.entity.PushList;
import com.cloudbroker.bcs.platform.ltb.middle.entity.UserEntity;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.PushListParam;
import com.cloudbroker.bcs.platform.ltb.middle.service.PushService;
import com.cloudbroker.bcs.platform.ltb.middle.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by daibd19671 on 2016/10/10.
 */
@Service
public class AdminPushBizServiceImpl implements AdminPushBizService{
    @Resource
    private UserService userService;
    @Resource
    private PushService pushService;

    @Override
    public PushBackVo sendPush(AdminNotifyForm adminNotifyForm) {
        //参数校验
        if (StringUtils.isEmpty(adminNotifyForm.getSend_mobile_list())) {
            if (adminNotifyForm.getPush_type().equals(PushType.REGISTRATION_ID.getVal())) {
                if (StringUtils.isEmpty(adminNotifyForm.getMobile())) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
            } else if (adminNotifyForm.getPush_type().equals(PushType.TAG.getVal())) {
                if (StringUtils.isEmpty(adminNotifyForm.getSend_mobile_list())
                        && StringUtils.isEmpty(adminNotifyForm.getTag())) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
            } else if (adminNotifyForm.getPush_type().equals(PushType.ALIAS.getVal())) {
                if (StringUtils.isEmpty(adminNotifyForm.getAlias_name())) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
            }
        }
        if(!checkMsgType(adminNotifyForm)){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.MSG_TYPE_ERR,PushBackVo.class);
        }
        if(adminNotifyForm.getMsg_type() != MsgType.ACTIVITY.getVal() &&
                adminNotifyForm.getMsg_type()!= MsgType.SYSTEM.getVal()){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.MSG_TYPE_ERR,PushBackVo.class);
        }
        NotifyForm notifyForm = new NotifyForm();
        BeanUtils.copyProperties(adminNotifyForm,notifyForm);
        notifyForm.setSendercomp_id(adminNotifyForm.getCompany_id());
        PushBackVo back = pushService.sendPush(notifyForm);
        return back;
    }

    @Override
    public PushBackVo bgsendPush(BgNotifyForm bgNotifyForm) {
        //西南
        if (bgNotifyForm.getSendercomp_id().equals("20020")) {
            if (bgNotifyForm.getPush_type().equals(PushType.TAG.getVal())) {
                if(StringUtils.isEmpty(bgNotifyForm.getTag())){
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
                XinanPushForm xpf = new XinanPushForm();
                xpf.setTag(bgNotifyForm.getTag());
                xpf.setCompany_id(bgNotifyForm.getSendercomp_id());
                xpf.setContent(bgNotifyForm.getContent());
                xpf.setRemark(bgNotifyForm.getRemark());
                if(bgNotifyForm.getPush_model_type().equals(PushModelType.COMBINE_APPLY_SUCCESS.getVal())){
                    xpf.setUserRemindType(UserRemindType.LEADER);
                    xpf.setXinanPushType(XinanPushType.COMBINE_APPLY_SUCCESS);
                }else if(bgNotifyForm.getPush_model_type().equals(PushModelType.COMBINE_CLOSE.getVal())){
                    xpf.setUserRemindType(UserRemindType.LEADER);
                    xpf.setXinanPushType(XinanPushType.COMBINE_CLOSE);
                }else if(bgNotifyForm.getPush_model_type().equals(PushModelType.COMBINE_UPDATE.getVal())){
                    xpf.setUserRemindType(UserRemindType.COMBINE);
                    xpf.setXinanPushType(XinanPushType.COMBINE_UPDATE);
                }else{
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.XINAN_PUSH_TYPE_ERR, PushBackVo.class);
                }
                return pushService.xinanTemplatePush(xpf);
            }else{
                return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.XINAN_PUSH_TYPE_ERR, PushBackVo.class);
            }
        } else {
            //国联
            if (bgNotifyForm.getPush_type().equals(PushType.REGISTRATION_ID.getVal())) {
                if (bgNotifyForm.getRegistration_id() == null) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
            } else if (bgNotifyForm.getPush_type().equals(PushType.TAG.getVal())) {
                if (StringUtils.isEmpty(bgNotifyForm.getTag())) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
            } else if (bgNotifyForm.getPush_type().equals(PushType.ALIAS.getVal())) {
                if (StringUtils.isEmpty(bgNotifyForm.getAlias_name())) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_PARAM_ERR, PushBackVo.class);
                }
            }
            NotifyForm notifyForm = new NotifyForm();
            notifyForm.setAlias_name(bgNotifyForm.getAlias_name());
//        notifyForm.setPush_time(bgNotifyForm.get);
            notifyForm.setUser_id(bgNotifyForm.getRegistration_id());
            //notifyForm.setMobile(bgNotifyForm.get);//TODO
//        notifyForm.setAdmin_id(bgNotifyForm.get);
//        notifyForm.setAdmin_name(bgNotifyForm.get);
//        notifyForm.setCombine_code(bgNotifyForm.get);
            notifyForm.setMessage_no(bgNotifyForm.getMessage_no());
            notifyForm.setContent(bgNotifyForm.getContent());
            notifyForm.setMessage_title(bgNotifyForm.getMessage_title());
//        notifyForm.setMsg_type(bgNotifyForm.get);
            notifyForm.setPush_type(bgNotifyForm.getPush_type());
            notifyForm.setPush_mode_type(bgNotifyForm.getPush_model_type());
            notifyForm.setSerial_no(bgNotifyForm.getSerial_no());
            notifyForm.setTag(bgNotifyForm.getTag());
            notifyForm.setTerminal_type(bgNotifyForm.getTerminal_type());
            notifyForm.setCompany_id(bgNotifyForm.getSendercomp_id());
            notifyForm.setSendercomp_id(bgNotifyForm.getSendercomp_id());
            PushBackVo back = pushService.bgsendPush(notifyForm);
            return back;
        }
    }
    @Override
    public PushListBackVo getPushList(PushListForm pushListForm) {
        pushListForm.setSendercomp_id(pushListForm.getCompany_id());
        PushListParam param = new PushListParam();
        BeanUtils.copyProperties(pushListForm,param);
        param.setNow(System.currentTimeMillis());
        Pagination page = new Pagination();
        page.setPage_no(pushListForm.getPage_no());
        page.setPage_size(pushListForm.getRequest_num());
        page.setPosition_str(pushListForm.getPosition_str());
        int count = pushService.countPushList(param);
        page.setTotal_item_num(count);
        page.calc();
        param.setPage(page);
        List<PushList> list = pushService.selectPushList(param);
        StringBuilder sb = new StringBuilder();
        for(PushList pushList : list){
            if(pushList.getPush_time() == null && StringUtils.isNotEmpty(pushList.getJpush_id())){
                sb.append(pushList.getJpush_id());
                sb.append(",");
            }
        }
        PushReportBack pushReportBack = null;
        String msg_ids = sb.toString();
        if (StringUtils.isNotEmpty(msg_ids)) {
            msg_ids = msg_ids.substring(0, msg_ids.length() - 1);
            PushReportVo pushReportVo = new PushReportVo();
            pushReportVo.setMsg_ids(msg_ids);
            pushReportVo.setCompany_id(pushListForm.getCompany_id());
            pushReportVo.setSendercomp_id(pushListForm.getSendercomp_id());
            pushReportBack = pushService.getPushReport(pushReportVo);
        }
        List<PushListData> dataList = new ArrayList<>(list.size());
        for(PushList pushList : list){
            PushListData temp = new PushListData();
            temp.setPush_id(pushList.getPush_id());
            temp.setSend_time(pushList.getCreate_time());
            temp.setMessage_title(pushList.getMessage_title());
            temp.setMsg_type(pushList.getMsg_type());
            temp.setAdmin_id(pushList.getAdmin_id());
            temp.setAdmin_name(pushList.getAdmin_name());
            temp.setContent(pushList.getContent());
            //判断是否定时推送
            if(pushList.getPush_time()!=null){
                temp.setSend_time(pushList.getPush_time());
                if(pushList.getPush_status().equals("0")){
                    temp.setSend_status(1);
                }else {
                    if (pushList.getPush_time() > System.currentTimeMillis()) {
                        temp.setSend_status(2);
                    } else {
                        temp.setSend_status(0);
                    }
                }
            }else{
                temp.setSend_status(0);
            }
            if (pushReportBack != null) {
                for (PushReportData prd : pushReportBack.getData_list()) {
                    if (pushList.getPush_time() == null &&
                            prd.getMsg_id() == Long.valueOf(pushList.getJpush_id())) {
                        temp.setTarget_num(0);
                        temp.setClick_rate(0d);
                        temp.setSend_arrive_rate(0d);
                    }
                }
            }
            dataList.add(temp);
        }
        PushListBackVo back = new PushListBackVo();
        back.setData_list(dataList);
        back.setRowcount(count);
        PushListBackVo retu = VOUtil.setSuccessResult(back);
        return retu;
    }


    @Override
    public HSBCPSBackVO tagAdd(AdminTagAdd form) {
        UserEntity temp = new UserEntity();
        temp.setUser_id(Long.valueOf(form.getApp_user_id()));
        UserEntity userEntity = userService.getUserEntity(temp);
        if(userEntity == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT,
                    HSBCPSBackVO.class);
        }
        TagsAddForm tagsAddForm = new TagsAddForm();
        tagsAddForm.setTag(form.getTag());
        tagsAddForm.setUser_id(userEntity.getUser_id());
        tagsAddForm.setCompany_id(userEntity.getCompany_id());
        tagsAddForm.setSendercomp_id(userEntity.getCompany_id());
        if(userEntity.getCompany_id().equals("20034")){
            return pushService.tagsAdd(tagsAddForm);
        }else{
            return pushService.xinanTagsAdd(tagsAddForm);
        }
    }

    @Override
    public HSBCPSBackVO tagDelete(AdminTagDelete form) {
        UserEntity temp = new UserEntity();
        temp.setUser_id(Long.valueOf(form.getApp_user_id()));
        UserEntity userEntity = userService.getUserEntity(temp);
        if(userEntity == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NOT_EXIT,
                    HSBCPSBackVO.class);
        }
        TagsRemoveForm tagsRemoveForm = new TagsRemoveForm();
        tagsRemoveForm.setTag(form.getTag());
        tagsRemoveForm.setUser_id(userEntity.getUser_id());
        tagsRemoveForm.setCompany_id(userEntity.getCompany_id());
        tagsRemoveForm.setSendercomp_id(userEntity.getCompany_id());
        if(userEntity.getCompany_id().equals("20034")){
            return pushService.tagsDelete(tagsRemoveForm);
        }else{
            return pushService.xinanTagsDelete(tagsRemoveForm);
        }
    }


    @Override
    public HSBCPSBackVO ennable_push(ManageEnableDisableScheduleVo form) {
        PushList temp = new PushList();
        temp.setPush_id(Long.valueOf(form.getPush_id()));
        temp.setCompany_id(form.getCompany_id());
        PushList pushList = pushService.getPushList(temp);
        if(pushList == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_LIST_ERR, HSBCPSBackVO.class);
        }
        if(pushList.getPush_time()==null || pushList.getPush_time()== 0L){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_SCHEDULE_ENNABLE_DISABLE_ERR,HSBCPSBackVO.class);
        }
        EnableDisableScheduleVo vo = new EnableDisableScheduleVo();
        BeanUtils.copyProperties(form,vo);
        vo.setSendercomp_id(form.getCompany_id());
        vo.setScheduleId(pushList.getJpush_id());
        HSBCPSBackVO back = pushService.ennable_push(vo);
        if(VOUtil.isSuccess(back)){
            pushList.setPush_status("1");
            pushService.updatePushList(pushList);
            return back;
        }else{
            return VOUtil.genBGErrorResult(back.getError_no(),back.getError_info(),HSBCPSBackVO.class);
        }
    }

    @Override
    public HSBCPSBackVO disable_push(ManageEnableDisableScheduleVo form) {
        PushList temp = new PushList();
        temp.setPush_id(Long.valueOf(form.getPush_id()));
        temp.setCompany_id(form.getCompany_id());
        PushList pushList = pushService.getPushList(temp);
        if(pushList == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_LIST_ERR, HSBCPSBackVO.class);
        }
        if(pushList.getPush_time()==null || pushList.getPush_time()== 0L){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_SCHEDULE_ENNABLE_DISABLE_ERR,HSBCPSBackVO.class);
        }
        EnableDisableScheduleVo vo = new EnableDisableScheduleVo();
        BeanUtils.copyProperties(form,vo);
        vo.setSendercomp_id(form.getCompany_id());
        vo.setScheduleId(pushList.getJpush_id());
        HSBCPSBackVO back = pushService.disable_push(vo);
        if(VOUtil.isSuccess(back)){
            pushList.setPush_status("0");
            pushService.updatePushList(pushList);
            return back;
        }else{
            return VOUtil.genBGErrorResult(back.getError_no(),back.getError_info(),HSBCPSBackVO.class);
        }
    }

    @Override
    public HSBCPSBackVO update_push(ManageUpdateScheduleVo form) {
        PushList temp = new PushList();
        temp.setPush_id(Long.valueOf(form.getPush_id()));
        temp.setCompany_id(form.getCompany_id());
        PushList pushList = pushService.getPushList(temp);
        if(pushList == null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_LIST_ERR, HSBCPSBackVO.class);
        }
        if(pushList.getPush_time()==null || pushList.getPush_time()== 0L){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.PUSH_SCHEDULE_ENNABLE_DISABLE_ERR,HSBCPSBackVO.class);
        }
        //TODO 根据电话查询reg_id
        UpdateScheduleVo vo = new UpdateScheduleVo();
        BeanUtils.copyProperties(form,vo);
        vo.setSendercomp_id(form.getCompany_id());
        vo.setScheduleId(pushList.getJpush_id());
        HSBCPSBackVO back = pushService.update_push(vo);
        if(VOUtil.isSuccess(back)){
            pushService.updatePushList(pushList);
            return back;
        }else{
            return VOUtil.genBGErrorResult(back.getError_no(),back.getError_info(),HSBCPSBackVO.class);
        }
    }


    private boolean checkMsgType(AdminNotifyForm adminNotifyForm){
        if (adminNotifyForm.getMsg_type() != MsgType.COMBINE.getVal() &&
                adminNotifyForm.getMsg_type() != MsgType.ACTIVITY.getVal() &&
                adminNotifyForm.getMsg_type() != MsgType.ASK.getVal() &&
                adminNotifyForm.getMsg_type() != MsgType.SYSTEM.getVal()){
            return false;
        }
        return true;
    }
}
